<template>
  <div class="system-logs">
    <h3>系统日志</h3>
    
    <div class="operation-bar">
      <div class="filters">
        <el-select v-model="logType" placeholder="日志类型" @change="filterLogs">
          <el-option label="全部" value="all"></el-option>
          <el-option label="登录日志" value="login"></el-option>
          <el-option label="操作日志" value="operation"></el-option>
          <el-option label="系统日志" value="system"></el-option>
          <el-option label="错误日志" value="error"></el-option>
        </el-select>
        
        <el-select v-model="logLevel" placeholder="日志级别" @change="filterLogs">
          <el-option label="全部" value="all"></el-option>
          <el-option label="INFO" value="info"></el-option>
          <el-option label="WARNING" value="warning"></el-option>
          <el-option label="ERROR" value="error"></el-option>
          <el-option label="CRITICAL" value="critical"></el-option>
        </el-select>
        
        <el-input
          v-model="searchQuery"
          placeholder="搜索日志内容..."
          style="width: 200px"
          clearable
          @keyup.enter="searchLogs"
        >
          <template #append>
            <el-button :icon="Search" @click="searchLogs"></el-button>
          </template>
        </el-input>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="filterLogs"
        ></el-date-picker>
      </div>
      
      <div class="actions">
        <el-button @click="refreshLogs">刷新</el-button>
        <el-button type="primary" @click="exportLogs">导出日志</el-button>
        <el-button type="danger" @click="clearLogs">清除日志</el-button>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="logs.length === 0" class="empty-container">
      <el-empty description="暂无日志数据" />
    </div>
    
    <el-table v-else :data="logs" style="width: 100%">
      <el-table-column type="expand">
        <template #default="props">
          <div class="log-details">
            <div><strong>IP地址:</strong> {{ props.row.ipAddress }}</div>
            <div><strong>用户代理:</strong> {{ props.row.userAgent }}</div>
            <div v-if="props.row.stackTrace"><strong>详细信息:</strong> <pre>{{ props.row.stackTrace }}</pre></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.timestamp) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="120">
        <template #default="scope">
          <el-tag :type="getLogTypeTag(scope.row.type)">{{ getLogTypeName(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="级别" width="100">
        <template #default="scope">
          <el-tag :type="getLogLevelTag(scope.row.level)" effect="dark">{{ scope.row.level }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户" width="120"></el-table-column>
      <el-table-column prop="message" label="内容" min-width="300" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="80">
        <template #default="scope">
          <el-button size="small" type="danger" @click="deleteLog(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和筛选
const searchQuery = ref('')
const logType = ref('all')
const logLevel = ref('all')
const dateRange = ref(null)

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 数据和状态
const loading = ref(true)
const logs = ref([])

// 初始化
onMounted(() => {
  fetchLogs()
})

// 获取日志列表
async function fetchLogs() {
  loading.value = true
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/admin/logs', {
    //   params: {
    //     page: currentPage.value,
    //     size: pageSize.value,
    //     query: searchQuery.value,
    //     type: logType.value !== 'all' ? logType.value : undefined,
    //     level: logLevel.value !== 'all' ? logLevel.value : undefined,
    //     startDate: dateRange.value ? dateRange.value[0] : undefined,
    //     endDate: dateRange.value ? dateRange.value[1] : undefined
    //   }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 800))
    
    logs.value = Array.from({ length: 20 }, (_, i) => {
      const types = ['login', 'operation', 'system', 'error']
      const type = types[Math.floor(Math.random() * types.length)]
      
      const levels = ['info', 'warning', 'error', 'critical']
      const level = levels[Math.floor(Math.random() * levels.length)]
      
      const messages = [
        '用户登录成功',
        '用户登录失败',
        '用户注销',
        '创建文档',
        '更新文档',
        '删除文档',
        '订阅文档',
        '取消订阅',
        '发送通知',
        '系统启动',
        '系统关闭',
        '数据库连接失败',
        '邮件发送失败',
        '访问权限不足'
      ]
      const message = messages[Math.floor(Math.random() * messages.length)]
      
      const users = ['admin', 'user1', 'user2', 'user3', 'system']
      const username = users[Math.floor(Math.random() * users.length)]
      
      return {
        id: i + 1,
        timestamp: new Date().getTime() - Math.floor(Math.random() * 10000000),
        type: type,
        level: level,
        username: username,
        message: message,
        ipAddress: `192.168.1.${Math.floor(Math.random() * 255)}`,
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        stackTrace: level === 'error' || level === 'critical' ? 'java.lang.Exception: 操作失败\n  at com.example.service.DocumentService.update(DocumentService.java:150)\n  at com.example.controller.DocumentController.updateDocument(DocumentController.java:85)' : null
      }
    })
    
    // 模拟筛选
    if (logType.value !== 'all') {
      logs.value = logs.value.filter(log => log.type === logType.value)
    }
    
    if (logLevel.value !== 'all') {
      logs.value = logs.value.filter(log => log.level === logLevel.value)
    }
    
    total.value = 200 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch logs:', error)
    ElMessage.error('获取日志失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
function formatDateTime(timestamp) {
  return new Date(timestamp).toLocaleString()
}

// 获取日志类型名称
function getLogTypeName(type) {
  switch (type) {
    case 'login':
      return '登录日志'
    case 'operation':
      return '操作日志'
    case 'system':
      return '系统日志'
    case 'error':
      return '错误日志'
    default:
      return '未知类型'
  }
}

// 获取日志类型标签颜色
function getLogTypeTag(type) {
  switch (type) {
    case 'login':
      return 'info'
    case 'operation':
      return 'success'
    case 'system':
      return 'warning'
    case 'error':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取日志级别标签颜色
function getLogLevelTag(level) {
  switch (level) {
    case 'info':
      return 'info'
    case 'warning':
      return 'warning'
    case 'error':
      return 'danger'
    case 'critical':
      return 'danger'
    default:
      return 'info'
  }
}

// 搜索日志
function searchLogs() {
  currentPage.value = 1
  fetchLogs()
}

// 筛选日志
function filterLogs() {
  currentPage.value = 1
  fetchLogs()
}

// 刷新日志
function refreshLogs() {
  fetchLogs()
}

// 导出日志
function exportLogs() {
  ElMessage.success('日志导出功能尚未实现')
  // 实际中这里会调用导出API
  // window.location.href = '/api/admin/logs/export?type=' + logType.value + '&level=' + logLevel.value + '&...
}

// 清除日志
async function clearLogs() {
  try {
    await ElMessageBox.confirm('确定要清除所有日志吗？此操作不可恢复。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete('/api/admin/logs')
    
    // 模拟清除成功
    logs.value = []
    total.value = 0
    
    ElMessage.success('日志清除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to clear logs:', error)
      ElMessage.error('清除日志失败')
    }
  }
}

// 删除单条日志
async function deleteLog(id) {
  try {
    await ElMessageBox.confirm('确定要删除此条日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/admin/logs/${id}`)
    
    // 模拟删除成功
    logs.value = logs.value.filter(log => log.id !== id)
    total.value--
    
    ElMessage.success('日志删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete log:', error)
      ElMessage.error('删除日志失败')
    }
  }
}

// 分页处理
function handleSizeChange(size) {
  pageSize.value = size
  fetchLogs()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchLogs()
}
</script>

<style scoped>
.system-logs {
  padding: 10px;
}

h3 {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.filters {
  display: flex;
  gap: 15px;
}

.actions {
  display: flex;
  gap: 10px;
}

.loading-container, 
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.log-details {
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
  line-height: 1.8;
}

.log-details pre {
  margin-top: 10px;
  padding: 10px;
  background: #f1f1f1;
  border-radius: 4px;
  overflow-x: auto;
  font-family: monospace;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 